<template>
	<div class="coupon-detail" v-loading="loading">
		<el-card shadow="hover">
			<div class="coupon-detail mb15">
				<ProdTreeSelector v-model="dialogVisible" :keyword="detailItem.searchKeyword" @getSkuList="getSkuList" />
				<el-form :inline="true" ref="ruleFormRef" :model="detailItem" :rules="rules" label-width="120px" class="demo-ruleForm">
					<el-row>
						<el-col :span="24">
							<el-form-item label="优惠券名称" prop="name">
								<el-input style="width: 400px" v-model="detailItem.name" placeholder="请输入优惠券名称" maxlength="200" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-col :span="24">
						<el-form-item label="有效期" prop="time">
							<el-date-picker
								v-model="detailItem.time"
								type="datetimerange"
								range-separator="To"
								start-placeholder="开始时间"
								end-placeholder="结束时间"
								format="YYYY-MM-DD HH:mm:ss"
							></el-date-picker>
							<span>（北京时间）</span>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="优惠券规则">
							<el-select v-model="detailItem.rule" placeholder style="width: 400px">
								<el-option v-for="item in COUPON_RULES_LIST" :key="item.value" :label="item.label" :value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="优惠条件">
							<div class="add-btn">
								<el-button color="#626aef" @click="addDiscount">添加优惠</el-button>
							</div>
							<div class="full-minus-list" v-show="detailItem.rule === FULL_MINUS">
								<div class="full-minus-header">
									<div class="full-minus-header-p">消费满</div>
									<div class="full-minus-header-p">订单减少</div>
									<div class="full-minus-header-p">优惠券库存</div>
								</div>
								<div class="full-minus-item" v-for="(item, index) in detailItem.fullMinusList" :key="`full-minus-item-${index}`">
									<div class="text-box">优惠{{ index + 1 }}</div>
									<div class="input-box">
										<el-select style="width: 100%" v-model="item.city" placeholder>
											<el-option v-for="ceil in cityList" :key="ceil.shorthand" :label="ceil.name" :value="ceil.shorthand"></el-option>
										</el-select>
									</div>
									<div class="input-box">
										<span class="input-currency">{{ getCurrencyUnit(item.city) }}</span>
										<el-input-number
											style="width: 100%"
											v-model="item.fullConsumption"
											:step="1"
											:controls="false"
											:min="0"
											:max="MAX_LENGTH"
											controls-position="right"
										/>
									</div>
									<div class="text-box">优惠金额</div>
									<div class="input-box">
										<span class="input-currency">{{ getCurrencyUnit(item.city) }}</span>
										<el-input-number
											style="width: 100%"
											v-model="item.orderReduction"
											:step="1"
											:controls="false"
											:min="0"
											:max="MAX_LENGTH"
											controls-position="right"
										/>
									</div>
									<div class="input-box">
										<el-input-number
											style="width: 100%"
											v-model="item.stock"
											:step="1"
											:controls="false"
											:min="0"
											:max="MAX_LENGTH"
											controls-position="right"
										/>
									</div>
									<div class="delete-box">
										<el-button type="danger" icon="ele-Close" circle @click="delFullMinusItem(index)" />
										<!-- <el-icon>
											<circle-close-filled @click="delFullMinusItem(index)" style="width: 20px; height: 20px" />
										</el-icon> -->
									</div>
								</div>
							</div>
							<div class="discount-list" v-show="detailItem.rule === DISCOUNT">
								<div class="discount-header">
									<div class="discount-header-p">消费满1件</div>
									<div class="discount-header-p">订单优惠</div>
									<div class="discount-header-p">优惠券库存</div>
								</div>
								<div class="discount-item" v-for="(item, index) in detailItem.discountList" :key="`full-minus-item-${index}`">
									<div class="text-box">优惠{{ index + 1 }}</div>
									<div class="input-box">
										<el-select style="width: 100%" v-model="item.city" placeholder>
											<el-option v-for="ceil in cityList" :key="ceil.shorthand" :label="ceil.name" :value="ceil.shorthand"></el-option>
										</el-select>
									</div>
									<div class="text-box">1件</div>
									<div class="text-box">享受折扣</div>
									<div class="input-box">
										<el-input-number
											style="width: 100%"
											v-model="item.discount"
											:step="0.1"
											:controls="false"
											:min="1"
											:max="10"
											controls-position="right"
										/>
										<span class="input-currency">折</span>
									</div>
									<div class="input-box">
										<el-input-number
											style="width: 100%"
											v-model="item.stock"
											:step="1"
											:controls="false"
											:min="0"
											:max="MAX_LENGTH"
											controls-position="right"
										/>
									</div>
									<div class="delete-box">
										<el-icon>
											<circle-close-filled @click="delDiscountItem(index)" style="width: 20px; height: 20px" />
										</el-icon>
									</div>
								</div>
							</div>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="使用商品">
							<div class="use-list">
								<div class="use-item">
									<div class="left-radio-box">
										<el-radio :disabled="importLoading" @change="clearTagsAndProductList()" v-model="detailItem.useRadio" :label="USE_GOODS_1">
											<span></span>
										</el-radio>
									</div>
									<div class="center-content">
										<div class="center-content-p">全部商品</div>
									</div>
									<div class="right-btn" v-if="detailItem.useRadio === USE_GOODS_1">
										<el-button type="success" @click="addType(`all`)">添加</el-button>
									</div>
								</div>
								<div class="use-item">
									<div class="left-radio-box">
										<el-radio :disabled="importLoading" @change="clearTagsAndProductList()" v-model="detailItem.useRadio" :label="USE_GOODS_2">
											<span></span>
										</el-radio>
									</div>
									<div class="center-content">
										<div class="center-content-input">
											<CateSelector v-model="detailItem.classificationId" />
										</div>
									</div>
									<div class="right-btn" v-if="detailItem.useRadio === USE_GOODS_2">
										<el-button type="success" @click="addType()">添加</el-button>
									</div>
								</div>
								<div class="use-item">
									<div class="left-radio-box">
										<el-radio :disabled="importLoading" @change="clearTagsAndProductList()" v-model="detailItem.useRadio" :label="USE_GOODS_3">
											<span></span>
										</el-radio>
									</div>
									<div class="center-content">
										<div class="center-content-input">
											<el-input v-model="detailItem.searchKeyword" placeholder="搜索商品" maxlength="200" @keyup.enter="searchProduct()" />
										</div>
									</div>
									<div class="right-btn" v-if="detailItem.useRadio === USE_GOODS_3">
										<el-button type="success" @click="searchProduct()">添加</el-button>
									</div>
								</div>
								<div class="use-item">
									<div class="left-radio-box">
										<el-radio :disabled="importLoading" @change="clearTagsAndProductList()" v-model="detailItem.useRadio" :label="USE_GOODS_4">
											<span></span>
										</el-radio>
									</div>
									<div class="center-content">
										<div class="center-content-input">
											<el-input
												v-model="detailItem.importKeyword"
												placeholder="批量导入：请输入商品名称用“，”隔开"
												maxlength="500"
												@keyup.enter="batchImport()"
											/>
										</div>
									</div>
									<div class="right-btn" v-if="detailItem.useRadio === USE_GOODS_4">
										<el-button type="success" @click="batchImport()" :loading="importLoading">添加</el-button>
									</div>
								</div>
							</div>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="已添加" v-if="detailItem.tags.length > 0">
							<el-tag class="coupon-detail-tag" v-for="tag in detailItem.tags" @close="closeTag(tag)" :key="tag.name" closable type="success">{{
								tag.name
							}}</el-tag>
						</el-form-item>
					</el-col>

					<div class="coupon-detail-table" v-if="detailItem.selectProductList.length > 0">
						<div class="coupon-detail-table-header">
							<div class="coupon-detail-table-header-left">
								<el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
							</div>
							<div class="coupon-detail-table-header-right">
								<el-button type="danger" @click="delSelectProductList">删除</el-button>
							</div>
						</div>
						<el-table v-loading="loading" :data="detailItem.selectProductList" style="width: 100%">
							<el-table-column label show-overflow-tooltip width="50px">
								<template #default="scope">
									<el-checkbox v-model="scope.row.isChecked" @change="handleCheckedCitiesChange" label></el-checkbox>
								</template>
							</el-table-column>
							<el-table-column prop="orderNumber" label="序号" show-overflow-tooltip width="80px"></el-table-column>
							<el-table-column prop="name" label="商品名称" show-overflow-tooltip></el-table-column>
							<el-table-column label="商品图片" width="100" show-overflow-tooltip>
								<template #default="scope">
									<el-image lazy :src="scope.row.imgUrl" :preview-src-list="srcList" :initial-index="scope.$index"></el-image>
								</template>
							</el-table-column>
							<el-table-column label="商品原价" show-overflow-tooltip>
								<template #default="scope">
									<span v-html="scope.row.originalPrice"></span>
								</template>
							</el-table-column>
							<el-table-column prop="sku" label="自编SKU" show-overflow-tooltip></el-table-column>
							<el-table-column prop="frequency" label="可使用次数（批量）" show-overflow-tooltip>
								<template #default="scope">
									<el-input-number
										style="width: 100%"
										v-model="scope.row.frequency"
										:step="1"
										:controls="false"
										:min="0"
										:max="MAX_LENGTH"
										controls-position="right"
									/>
								</template>
							</el-table-column>
						</el-table>
					</div>
					<div class="coupon-detail-btns">
						<el-button @click="cancel" :loading="submitLoading">取消</el-button>
						<el-button type="primary" @click="submitForm()" :loading="submitLoading">保存</el-button>
					</div>
				</el-form>
			</div>
		</el-card>
	</div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { storeToRefs } from 'pinia';
import dayjs from 'dayjs';
import { useSite } from '/@/stores/siteList';
import CateSelector from '/@/components/common/CateSelector.vue';
import useCouponState from '/@/utils/pageState/couponState';
import { cateFormat } from '/@/utils/filters';
import { isEmpty } from '/@/utils';
import { getCommonSiteList, getCurrencyUnit } from '/@/utils/commonRequest';
import { useCouponApi } from '/@/api/coupon';
import ProdTreeSelector from '/@/components/common/prodTreeSelector/ProdTreeSelector.vue';
const { COUPON_RULES_LIST, DISCOUNT, FULL_MINUS, getPriceByField, MAX_LENGTH, USE_GOODS_1, USE_GOODS_2, USE_GOODS_3, USE_GOODS_4 } = useCouponState();
const { addCoupon, getCouponDetail, getSkuListByName, UpdateCoupon } = useCouponApi();
const { proxy } = getCurrentInstance();

const storesSite = useSite();
const { storeSiteList } = storeToRefs(storesSite);
const route = useRoute();

const couponId = route.params.id;
console.log('111', couponId);

// const props = defineProps({
// 	couponId: {
// 		type: Number,
// 		default: -1,
// 	},
// });
// const emit = defineEmits(['update:couponId', 'reloadList']);
const ruleFormRef = ref(null);
let loading = ref(false);
let submitLoading = ref(false);
let dialogVisible = ref(false);
let isReady = ref(false);
let importLoading = ref(false);
let checkAll = ref(false);
let isIndeterminate = ref(false);
let srcList = ref([]);
let cityList = ref([]);
let detailItem = ref({
	id: '',
	time: [null, null],
	name: '',
	rule: FULL_MINUS,
	fullMinusList: [
		{
			city: '',
			fullConsumption: 0,
			orderReduction: 0,
			stock: MAX_LENGTH,
		},
	],
	discountList: [
		{
			city: '',
			discount: 1,
			stock: MAX_LENGTH,
		},
	],
	useRadio: USE_GOODS_1,
	classificationId: 0,
	searchKeyword: '',
	importKeyword: '',
	tags: [],
	selectProductList: [],
});
let rules = {
	name: [
		{
			required: true,
			message: '请输入优惠券名称',
			trigger: 'blur',
		},
	],
	time: [
		{
			required: true,
			message: '请选择有效期',
			trigger: 'blur',
			validator: (rule, value) => {
				return value[0] !== null && value[1] !== null;
			},
		},
	],
};

init();
function init() {
	getCityList();
	setDefaultDiscount();
	if (couponId === '0') {
		return;
	}
	getDetail();
}

function setDefaultDiscount() {
	let list = storeSiteList.value;
	let shorthand = '';
	if (list.length > 0) {
		shorthand = list[0].shorthand;
	}
	detailItem.value.fullMinusList[0].city = shorthand;
	detailItem.value.discountList[0].city = shorthand;
}

async function getDetail() {
	loading.value = true;
	try {
		let params = {
			id: couponId,
		};
		let res = await getCouponDetail(params.id);
		if (res.code !== 200) {
			loading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		let tempItem = res.data;
		let fullMinusList = [],
			discountList = [],
			tags = [],
			selectProductList = [];
		if (tempItem.discountItermList !== null) {
			if (tempItem.type === FULL_MINUS) {
				fullMinusList = tempItem.discountItermList.map((ceil) => {
					return {
						city: ceil.platformCode,
						fullConsumption: ceil.amountNum,
						orderReduction: ceil.amount,
						stock: ceil.publishCount,
					};
				});
			}
			if (tempItem.type === DISCOUNT) {
				discountList = tempItem.discountItermList.map((ceil) => {
					return {
						city: ceil.platformCode,
						discount: ceil.discount ? ceil.discount * 10 : ceil.discount,
						stock: ceil.publishCount,
					};
				});
			}
		}

		if (tempItem.productCategoryList !== null) {
			tags = tempItem.productCategoryList.map((ceil) => {
				return {
					id: ceil.id,
					name: ceil.name,
				};
			});
			tags = Array.from(new Set([...tags]));
		}

		if (tempItem.useType === USE_GOODS_1) {
			tags = [
				{
					id: 0,
					name: '全部商品',
				},
			];
		}

		if (tempItem.skuStockList !== null) {
			selectProductList = tempItem.skuStockList.map((ceil, index) => {
				return {
					id: ceil.id,
					isChecked: false,
					orderNumber: index + 1,
					name: ceil.productName,
					imgUrl: ceil.pic,
					originalPrice:
						getPriceByField(ceil.euPrice, 'euPrice') +
						'<br/>' +
						getPriceByField(ceil.ukPrice, 'ukPrice') +
						'<br/>' +
						getPriceByField(ceil.usPrice, 'usPrice'),
					sku: ceil.skuCode,
					frequency: ceil.limitNum,
				};
			});
		}

		detailItem.value = {
			id: tempItem.name,
			time: [tempItem.startTime, tempItem.endTime],
			name: tempItem.name,
			rule: tempItem.type,
			fullMinusList,
			discountList,
			useRadio: tempItem.useType,
			classificationId: 0,
			searchKeyword: '',
			importKeyword: '',
			tags,
			selectProductList,
		};
		loading.value = false;
		isReady.value = true;
	} catch (error) {
		loading.value = false;
		ElMessage({
			type: 'error',
			message: '获取详情失败',
		});
	}
}

async function getCityList() {
	cityList.value = await getCommonSiteList();
	console.log('9-----', cityList.value);
	try {
		console.log(111);
	} catch (error) {
		console.log('error', error);
	}
}

function submitForm() {
	ruleFormRef.value.validate((valid) => {
		if (valid) {
			// alert('submit!')
			submit();
		} else {
			// console.log("error submit!!")
			return false;
		}
	});
}

async function submit() {
	submitLoading.value = true;
	try {
		let params = {};
		let res = null;
		const item = detailItem.value;
		let discountItermList = [],
			categoryIdList = [],
			couponSkuRelationList = [],
			isErr = false,
			time = item.time === null ? [null, null] : item.time;

		if (item.rule === FULL_MINUS) {
			discountItermList = item.fullMinusList.map((ceil) => {
				if (ceil.orderReduction > ceil.fullConsumption) {
					isErr = true;
				}
				return {
					amount: ceil.orderReduction,
					amountNum: ceil.fullConsumption,
					count: 0,
					discount: 0,
					minPoint: 0,
					perLimit: 0,
					platformCode: ceil.city,
					publishCount: ceil.stock,
				};
			});
		}
		if (isErr) {
			submitLoading.value = false;
			ElMessage({
				type: 'info',
				message: '消费满的值不得大于订单减少的值！',
			});
			return;
		}

		if (item.rule === DISCOUNT) {
			discountItermList = item.discountList.map((ceil) => {
				let discount = ceil.discount;
				return {
					amount: 0,
					amountNum: 0,
					count: 0,
					discount: discount ? discount / 10 : discount,
					minPoint: 0,
					perLimit: 0,
					platformCode: ceil.city,
					publishCount: ceil.stock,
				};
			});
		}

		if (discountItermList.length === 0) {
			submitLoading.value = false;
			ElMessage({
				type: 'info',
				message: '请添加优惠条件！',
			});
			return;
		}

		categoryIdList = item.tags.map((ceil) => {
			return ceil.id;
		});
		categoryIdList = Array.from(new Set([...categoryIdList]));

		if (item.useRadio === USE_GOODS_1) {
			categoryIdList = [];
		}
		couponSkuRelationList = item.selectProductList.map((ceil) => {
			return {
				skuId: ceil.id,
				limitNum: ceil.frequency,
			};
		});

		// 新增
		if (couponId === 0) {
			params = {
				name: item.name,
				startTime: time[0] !== null ? dayjs(time[0]).format('YYYY-MM-DD[T]HH:mm:ss[Z]') : '',
				endTime: time[1] !== null ? dayjs(time[1]).format('YYYY-MM-DD[T]HH:mm:ss[Z]') : '',
				type: item.rule,
				discountItermList,
				useType: item.useRadio,
				categoryIdList,
				couponSkuRelationList,
			};
			res = await addCoupon(params);
		}
		// 修改
		else {
			params = {
				couponId: couponId,
				name: item.name,
				startTime: time[0] !== null ? dayjs(time[0]).format('YYYY-MM-DD[T]HH:mm:ss[Z]') : '',
				endTime: time[1] !== null ? dayjs(time[1]).format('YYYY-MM-DD[T]HH:mm:ss[Z]') : '',
				type: item.rule,
				discountItermList,
				useType: item.useRadio,
				categoryIdList,
				couponSkuRelationList,
			};
			res = await UpdateCoupon(params);
		}

		if (res.code !== 200) {
			submitLoading.value = false;
			return;
		}
		submitLoading.value = false;
		ElMessage({
			type: 'success',
			message: '保存成功！',
		});
		onReloadProductList();
		closeCurrentTagsView();
	} catch (error) {
		submitLoading.value = false;
		ElMessage({
			type: 'error',
			message: '保存失败',
		});
	}
}

function cancel() {
	ElMessageBox.confirm(`将丢失未保存数据，是否继续退出编辑？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			closeCurrentTagsView();
		})
		.catch(() => {});
}

const onReloadProductList = () => {
	proxy.mittBus.emit('onReloadProductList');
};

// 关闭当然商品编辑tabs
const closeCurrentTagsView = () => {
	let path = route.meta.isDynamicPath ? route.meta.isDynamicPath : route.path;
	proxy.mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, path, meta: route.meta }));
};

function addDiscount() {
	let state = detailItem.value.rule;
	let list = storeSiteList.value;
	let shorthand = '';
	if (list.length > 0) {
		shorthand = list[0].shorthand;
	}
	if (state === FULL_MINUS) {
		detailItem.value.fullMinusList.push({
			city: shorthand,
			fullConsumption: 0,
			orderReduction: 0,
			stock: MAX_LENGTH,
		});
	} else {
		detailItem.value.discountList.push({
			city: shorthand,
			discount: 1,
			stock: MAX_LENGTH,
		});
	}
}

function delFullMinusItem(index) {
	if (index === 0) {
		return;
	}
	detailItem.value.fullMinusList.splice(index, 1);
}

function delDiscountItem(index) {
	detailItem.value.discountList.splice(index, 1);
}

function addType(params) {
	if (params) {
		if (detailItem.value.tags.length === 1) {
			ElMessage({
				type: 'info',
				message: '全部商品类型只能添加一次',
			});
			return;
		}

		detailItem.value.tags.push({ name: '全部商品', id: 'params' });
		return;
	}
	console.log('0--9-', detailItem.value);
	let classificationId = detailItem.value.classificationId;
	if (isEmpty(classificationId) || classificationId === 0) {
		return;
	}
	detailItem.value.tags.push({ name: `${cateFormat(classificationId)}`, id: classificationId });
	detailItem.value.tags = duplicateRemovalById(detailItem.value.tags);
}

function closeTag(tag) {
	detailItem.value.tags.splice(detailItem.value.tags.indexOf(tag), 1);
}

function clearTagsAndProductList() {
	detailItem.value.tags = [];
	detailItem.value.selectProductList = [];
}
function searchProduct() {
	if (detailItem.value.useRadio !== USE_GOODS_3) {
		return;
	}
	// 去打开搜索商品的弹窗
	dialogVisible.value = true;
}

// 搜索到的列表的回调
let getSkuList = (skuList) => {
	let tempSelectProductList = [];
	tempSelectProductList = skuList.map((ceil, index) => {
		return {
			id: ceil.id,
			isChecked: false,
			orderNumber: detailItem.value.selectProductList.length + index + 1,
			name: ceil.productName,
			imgUrl: ceil.pic,
			originalPrice:
				getPriceByField(ceil.euPrice, 'euPrice') +
				'<br/>' +
				getPriceByField(ceil.ukPrice, 'ukPrice') +
				'<br/>' +
				getPriceByField(ceil.usPrice, 'usPrice'),
			sku: ceil.skuCode,
			frequency: MAX_LENGTH,
		};
	});
	detailItem.value.selectProductList = [...detailItem.value.selectProductList, ...tempSelectProductList];
	detailItem.value.selectProductList = duplicateRemovalById(detailItem.value.selectProductList);
	importLoading.value = false;
};

function batchImport() {
	if (detailItem.value.useRadio !== USE_GOODS_4 || importLoading.value) {
		return;
	}
	let text = detailItem.value.importKeyword;
	if (isEmpty(text)) {
		ElMessage({
			type: 'info',
			message: '请输入商品名称用“，”隔开',
		});
		return;
	}
	batchImportFun();
}

async function batchImportFun() {
	importLoading.value = true;
	try {
		let params = {
			name: detailItem.value.importKeyword,
		};
		let res = await getSkuListByName(params);
		if (res.code !== 200) {
			importLoading.value = false;
			return;
		}
		if (res.data.length === 0) {
			importLoading.value = false;
			ElMessage({
				type: 'info',
				message: '暂无商品',
			});
			return;
		}
		let tempList = res.data.map((item, index) => {
			return {
				id: item.id,
				isChecked: false,
				orderNumber: detailItem.value.selectProductList.length + index + 1,
				name: item.productName,
				imgUrl: item.pic,
				originalPrice:
					getPriceByField(item.euPrice, 'euPrice') +
					'<br/>' +
					getPriceByField(item.ukPrice, 'ukPrice') +
					'<br/>' +
					getPriceByField(item.usPrice, 'usPrice'),
				sku: item.skuCode,
				frequency: MAX_LENGTH,
			};
		});
		if (tempList.length > 0) {
			checkAll.value = false;
		}
		detailItem.value.selectProductList = [...detailItem.value.selectProductList, ...tempList];
		detailItem.value.selectProductList = duplicateRemovalById(detailItem.value.selectProductList);
		setSrcList(detailItem.value.selectProductList);
		importLoading.value = false;
	} catch (error) {
		importLoading.value = false;
		ElMessage({
			type: 'error',
			message: '搜索商品失败',
		});
	}
}

function setSrcList(list) {
	srcList.value = list.map((item) => {
		return item.imgUrl ? item.imgUrl : '';
	});
}

function setAllChecked(state) {
	let productList = detailItem.value.selectProductList;
	let tempList = productList.map((item) => {
		item.isChecked = state;
		return item;
	});
	detailItem.value.selectProductList = tempList;
}

function delSelectProductList() {
	let productList = detailItem.value.selectProductList;
	let newList = productList.filter((item) => {
		if (!item.isChecked) {
			return item;
		}
	});
	detailItem.value.selectProductList = newList;
}

function handleCheckAllChange(val) {
	isIndeterminate.value = false;
	setAllChecked(val);
}

function handleCheckedCitiesChange(val) {
	let productList = detailItem.value.selectProductList;
	let checkedCount = 0;
	productList.map((item) => {
		if (item.isChecked) {
			checkedCount++;
		}
	});
	checkAll.value = checkedCount === productList.length;
	isIndeterminate.value = checkedCount > 0 && checkedCount < productList.length;
}

function duplicateRemovalById(list) {
	if (list.length === 0) {
		return [];
	}
	let newList = [];
	for (let i = 0; i < list.length; i++) {
		for (var j = i + 1; j < list.length; j++) {
			if (list[i].id == list[j].id) {
				++i;
			}
		}
		newList.push(list[i]);
	}
	return newList;
}

defineExpose({
	cancel,
	submitForm,
});
</script>

<style lang="scss" scoped>
.coupon-detail {
	max-width: 1200px;
	margin: 0 auto;
	.coupon-detail-btns {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 20px;
	}
	.coupon-detail-tag {
		margin-right: 10px;
	}
	.add-btn {
		display: block;
		width: 100%;
	}
	.full-minus-list {
		width: 80 * 2 + 160 * 4 + 30+ 0px;
		display: flex;
		flex-direction: column;
		.full-minus-header {
			width: 100%;
			display: flex;
			.full-minus-header-p {
				display: flex;
				justify-content: flex-end;
				&:nth-child(1) {
					width: 80+160+160+0px;
					padding-right: 20px;
				}
				&:nth-child(2) {
					width: 80+160px;
					padding-right: 20px;
				}
				&:nth-child(3) {
					flex: 1;
					padding-right: 10+30px;
				}
			}
		}
		.full-minus-item {
			display: flex;
			width: 100%;
			margin-bottom: 20px;
			.text-box {
				width: 80px;
				padding-right: 10px;
				text-align: center;
			}
			.input-box {
				width: 160px;
				display: flex;
				padding-right: 10px;
				.input-currency {
					padding-right: 5px;
				}
			}
		}
		.delete-box {
			width: 30px;
			color: red;
			display: flex;
			justify-content: center;
			cursor: pointer;
		}
	}
	.discount-list {
		width: 80 * 3 + 160 * 3 + 30 + 0px;
		display: flex;
		flex-direction: column;
		.discount-header {
			width: 100%;
			display: flex;
			.discount-header-p {
				display: flex;
				justify-content: flex-end;
				&:nth-child(1) {
					width: 80+160+80+0px;
					padding-right: 15px;
				}
				&:nth-child(2) {
					width: 80+160px;
					padding-right: 30px;
				}
				&:nth-child(3) {
					flex: 1;
					padding-right: 10+30px;
				}
			}
		}
		.discount-item {
			display: flex;
			width: 100%;
			margin-bottom: 10px;
			.text-box {
				width: 80px;
				padding-right: 10px;
				text-align: center;
			}
			.input-box {
				width: 160px;
				display: flex;
				padding-right: 10px;
				.input-currency {
					padding-left: 5px;
				}
			}
		}
		.delete-box {
			width: 30px;
			margin-top: 8px;
			color: red;
			display: flex;
			justify-content: center;
			cursor: pointer;
		}
	}
	.use-list {
		width: 100%;
		.use-item {
			display: flex;
			width: 100%;
			margin-bottom: 10px;
			.left-radio-box {
			}
			.center-content {
				min-width: 400px;
				.center-content-p {
				}
				.center-content-input {
					width: 100%;
				}
			}
			.right-btn {
				margin-left: 20px;
			}
		}
	}
	.coupon-detail-table-header {
		display: flex;
		align-items: center;
		justify-content: center;
		padding-bottom: 10px;
		.coupon-detail-table-header-left {
			flex: 1;
		}
		.coupon-detail-table-header-right {
			width: 100px;
			text-align: right;
		}
	}
}
</style>
